﻿using System;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using NJGZBTYHXT.Properties;
using System.Drawing;
using System.Data;
using Common.Excel;
using System.Diagnostics;

namespace NJGZBTYHXT
{
    public partial class Agbyh : Form
    {
        #region 字段与属性

        /// <summary>
        /// 每次摇出国补金额
        /// </summary>
        private int _mcCount = 0;
        private int _mcBxCount = 0;
        /// <summary>
        /// 总共摇出国补金额
        /// </summary>
        private int _gbCount = 0;
        /// <summary>
        /// 摇号次数
        /// </summary>
        private int _yhcs = 0;
        /// <summary>
        /// 已摇号次数
        /// </summary>
        private int _yycs = 0;
        /// <summary>
        /// 源数据
        /// </summary>
        private DataGridView _dgv;
        /// <summary>
        /// 源数据
        /// </summary>
        public DataGridView Dgv
        {
            get { return _dgv; }
            set { _dgv = value; }
        }
        /// <summary>
        /// 候选设置类
        /// </summary>
        private FirstOption xh;
        /// <summary>
        /// 列名
        /// </summary>
        private string _columnName;
        /// <summary>
        /// 列名
        /// </summary>
        public string ColumnName
        {
            get { return _columnName; }
            set { _columnName = value; }
        }
        /// <summary>
        /// 列显示名
        /// </summary>
        private string _columnHeadText;
        /// <summary>
        /// 列显示名
        /// </summary>
        public string ColumnHeadText
        {
            get { return _columnHeadText; }
            set { _columnHeadText = value; }
        }
        /// <summary>
        /// 备选列表
        /// </summary>
        private ArrayList nums;

        /// <summary>
        /// 结果序号数组
        /// </summary>
        private int[] _jg;
        /// <summary>
        /// 结果序号数组
        /// </summary>
        public int[] Jg
        {
            get { return _jg; }
            set { _jg = value; }
        }

        private RandomArray ra = new RandomArray();
        private string title;

        #endregion

        public Agbyh()
        {
            InitializeComponent();
            //this.dataGridView1.RowPostPaint += new DataGridViewRowPostPaintEventHandler(Program.dataGridView1_RowPostPaint);
        }

        /// <summary>
        /// 开始|停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (_yycs == 0)
            {
                if (textBox1.Text.Trim() == "")
                {
                    MessageBox.Show("请输入" + label1.Text, "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    textBox1.Focus();
                    return;
                }
                if (textBox3.Text.Trim() == "")
                {
                    MessageBox.Show("请输入" + label3.Text, "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    textBox3.Focus();
                    return;
                }

                _gbCount = int.Parse(textBox1.Text.Trim());
                _mcCount = int.Parse(textBox3.Text.Trim());

                if (_gbCount % _mcCount == 0) { _yhcs = _gbCount / _mcCount; } else { _yhcs = _gbCount / _mcCount + 1; }

                dataGridView1.Visible = true;

                FirstOption.DataGridViewSHC(dataGridView1, "ID,姓名,证件号码,国补总额（元）,省补总额（元）", true, true);
            }

            if (button1.Text != "开始")
            {
                button1.Text = "开始";
                button1.Image = Resources.play_l;
                timer1.Enabled = false;
                button5.Enabled = button2.Enabled = button3.Enabled = button4.Enabled = true;
                _yycs++;

                if (_yycs >= _yhcs)
                {
                    button1.Image = Resources.play_h;
                    button1.Enabled = false;
                }
                _mcBxCount = 0;
                LoadRandomData();
            }
            else
            {
                if (_dgv.Rows.Count > 0)
                {
                    button1.Text = "停止";
                    button1.Image = Resources.stop_h;
                    timer1.Enabled = true;
                    button5.Enabled = button2.Enabled = button3.Enabled = button4.Enabled = false;
                }
                else
                {
                    MessageBox.Show("系统提示：没有检索到数据源", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }

        /// <summary>
        /// 加载显示信息
        /// </summary>
        private void LoadText()
        {
            int gbze = 0, sbze = 0;

            foreach (int index in nums)
            {
                DataGridViewRow row = _dgv.Rows[index];
                int gb = int.Parse(row.Cells["国补总额（元）"].Value.ToString());
                int sb = int.Parse(row.Cells["省补总额（元）"].Value.ToString());
                gbze += gb;
                sbze += sb;
            }
            toolStripStatusLabel1.Text = string.Format("摇号次数:{0}/{1}  摇出条数:{2}  国补总额(元):{3}  省补总额(元):{4}", _yycs, _yhcs, nums.Count, gbze, sbze);
        }

        /// <summary>
        /// 加载随机摇号数据
        /// </summary>
        private void LoadRandomData()
        {
            try
            {
                int[] jg = new int[0];

                ///开启候选
                if (xh.IsOpen)
                {
                    //获取候选列表
                    int[] listIndexs = xh.SelectData(_dgv);

                    int[] jg1 = HXYH(listIndexs, _mcCount);

                    int[] jg2 = new int[0];

                    if (_mcBxCount < _mcCount)
                    {
                        jg2 = YHJE(_mcCount - _mcBxCount);
                    }

                    jg = new int[jg1.Length + jg2.Length];

                    for (int i = 0; i < jg1.Length + jg2.Length; i++)
                    {
                        if (i < jg1.Length)
                        {
                            jg[i] = jg1[i];
                        }
                        else
                        {
                            jg[i] = jg2[i - jg1.Length];
                        }
                    }
                }
                else
                {
                    jg = YHJE(_mcCount);
                }

                LoadText();

                dataGridView1.Rows.Clear();

                foreach (int index in jg)
                {
                    DataGridViewRow row = _dgv.Rows[index];
                    object[] columnValues = new object[row.Cells.Count];
                    for (int i = 0; i < columnValues.Length; i++)
                    {
                        columnValues[i] = row.Cells[i].Value;
                    }
                    dataGridView1.Rows.Add(columnValues);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private int[] HXYH(int[] listIndexs, int jeCount)
        {
            int je = 0;
            ArrayList list = new ArrayList();

            int[] indexs = listIndexs;

            int index = 0;

            while (je < jeCount && index < indexs.Length)
            {
                if (!nums.Contains(indexs[index]))
                {
                    int gbze = int.Parse(_dgv.Rows[indexs[index]].Cells[_columnName].Value.ToString());

                    je += gbze;

                    if (je > jeCount)
                    {
                        je -= gbze;
                    }
                    else
                    {
                        list.Add(indexs[index]);
                        nums.Add(indexs[index]);
                    }
                }
                index++;
            }

            _mcBxCount = je;

            int[] rs = new int[list.Count];

            for (int i = 0; i < list.Count; i++)
            {
                rs[i] = int.Parse(list[i].ToString());
            }
            return rs;
        }

        /// <summary>
        /// 按金额摇号
        /// </summary>
        /// <param name="jeCount">总额</param>
        /// <returns></returns>
        private int[] YHJE(int jeCount)
        {
            int je = 0;
            ArrayList list = new ArrayList();

            ra.MinValue = 0;
            ra.MaxValue = _dgv.Rows.Count - 1;
            int[] indexs = ra.Start(_dgv.Rows.Count - 1);

            int index = 0;
            while (je < jeCount && index < indexs.Length)
            {
                if (!nums.Contains(indexs[index]))
                {
                    int gbze = int.Parse(_dgv.Rows[indexs[index]].Cells[_columnName].Value.ToString());

                    je += gbze;

                    if (je > jeCount)
                    {
                        je -= gbze;
                    }
                    else
                    {
                        list.Add(indexs[index]);
                        nums.Add(indexs[index]);
                    }
                }
                index++;
            }

            _mcBxCount = je;

            int[] rs = new int[list.Count];

            for (int i = 0; i < list.Count; i++)
            {
                rs[i] = int.Parse(list[i].ToString());
            }
            return rs;
        }

        /// <summary>
        /// 生成Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string path = Application.StartupPath + @"\Excel\";

                if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

                string filePath = path + DateTime.Now.ToFileTime() + ".xls";

                FirstOption.OutExcel(dataGridView1, filePath);

                if (DialogResult.OK == MessageBox.Show("生成Excel成功，文件路径为：\n" + filePath + "\n是否打开文件？", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Process.Start(filePath);
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 取消退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 数据初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Agbyh_Load(object sender, EventArgs e)
        {
            title = this.Text;
            this.Text = title + "补金额摇号";
            label1.Text = "总共摇出" + title + "补金额：";
            label3.Text = "每次摇出" + title + "补金额：";

            xh = new FirstOption();
            nums = new ArrayList();

            foreach (DataGridViewColumn dgvr in _dgv.Columns)
            {
                dataGridView1.Columns.Add(dgvr.Name, dgvr.HeaderText);
            }

            dataGridView1.Columns["ID"].DisplayIndex = 0;

            dataGridView1.Visible = false;
        }

        /// <summary>
        /// 滚动选号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (_dgv.Rows.Count > 0)
            {
                ra.MinValue = 0;
                ra.MaxValue = _dgv.Rows.Count - 1;
                int[] indexs = ra.Start(10);

                dataGridView1.Rows.Clear();

                foreach (int index in indexs)
                {
                    DataGridViewRow row = _dgv.Rows[index];
                    object[] columnValues = new object[row.Cells.Count];
                    for (int i = 0; i < columnValues.Length; i++)
                    {
                        columnValues[i] = row.Cells[i].Value;
                    }
                    dataGridView1.Rows.Add(columnValues);
                }
            }
        }

        /// <summary>
        /// 查看结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            YHJG yhjg = new YHJG();
            yhjg.dgv = dataGridView1;
            yhjg.ShowDialog(this);
        }

        private void Agbyh_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.timer1.Enabled = false;
            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 确认完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + @"\excel\";

            if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }

            string filePath = path + DateTime.Now.ToFileTime() + ".xls";

            DataTable dtSource = new DataTable();

            string[] cs = new string[] { 
                        "id", "市", "县", "乡镇", "村", "地址", "受益户身份", "手机号码", "姓名", "性别", "联系电话", "证件号码", "出生日期", "文化程度", 
                        "主要农作物", "耕地面积", "机具大类", "机具小类", "机具品目", "机具型号", "机具编号", "指标确认书编号", "数量", "特殊设备数量", 
                        "生产企业", "单台国补（元）", "国补总额（元）", "单台省补（元）", "省补总额（元）", "单台市补（元）", "单台县补（元）", "备注", 
                        "状态", "录入日期" };

            NPOIHelper.ListColumnsName = new SortedList(new MyComparer());

            foreach (string csname in cs)
            {
                Common.Excel.NPOIHelper.ListColumnsName.Add(csname, csname);
            }

            foreach (DataGridViewColumn column in _dgv.Columns)
            {
                dtSource.Columns.Add(column.Name);
            }

            _jg = new int[nums.Count];

            int j = 0;

            foreach (int index in nums)
            {
                _jg[j] = index;
                j++;

                DataGridViewRow row = _dgv.Rows[index];
                object[] values = new object[dtSource.Columns.Count];
                for (int i = 0; i < dtSource.Columns.Count; i++)
                {
                    values[i] = row.Cells[dtSource.Columns[i].ColumnName].Value;
                }
                dtSource.Rows.Add(values);
            }

            NPOIHelper.ExportExcel(dtSource, filePath);

            xh.Delete();

            if (DialogResult.Yes == MessageBox.Show("确认退出该窗口吗？", "温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                this.Close();
                //Process.Start(filePath);
            }
        }
    }
}
